package com.hy.domain;

import java.util.Date;
import java.util.List;

import javax.persistence.ManyToOne;
import javax.persistence.Query;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findNewsByType" })
public class News {

    @Size(min = 2)
    private String name;

    @Size(max = 40000)
    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date updateTime;

    @Size(min = 2)
    private String author;

    private Integer hits = 0;

    @ManyToOne
    private NewType type;

    @ManyToOne
    private NewSource source;
    
    private String keywords;
    
	private String description;
    
    public News getUp(){
    	News news = null;
    	try {
    		TypedQuery<News> query = entityManager().createQuery("from News n where n.id < :id and n.type = :type order by n.id desc", News.class);
        	query.setParameter("id", this.getId());
        	query.setParameter("type", type);
        	query.setFirstResult(0).setMaxResults(1);
        	news = query.getSingleResult();
		} catch (Exception e) {
		}
    	return news;
    }
    
    public News getNext(){
    	News news = null;
    	try {
    		TypedQuery<News> query = entityManager().createQuery("from News n where n.id > :id and n.type = :type", News.class);
        	query.setParameter("id", this.getId());
        	query.setParameter("type", type);
        	query.setFirstResult(0).setMaxResults(1);
        	news = query.getSingleResult();
		} catch (Exception e) {
		}
    	return news;
    }
    
    public static List<News> getNews(NewType type, int first, int max){
    	List<News> news = null;
    	try {
    		TypedQuery<News> query = entityManager().createQuery("from News n where n.type = :type order by n.id desc", News.class);
    		query.setParameter("type", type);
    		query.setFirstResult(first).setMaxResults(max);
    		news = query.getResultList();
		} catch (Exception e) {
		}
    	return news;
    }
    
    public static long countType(NewType type){
    	long count = -1;
    	try {
			Query query = entityManager().createQuery("select count(n) from News n where n.type = :type");
			query.setParameter("type", type);
			count = (Long)query.getSingleResult();
		} catch (Exception e) {
		}
    	return count;
    }
    
}
